﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using EFBasic.Entities;

namespace EFBasic
{
    public class BaseRepository<T> where T : BaseEntity
    {
        protected DbContext DbContext;
        protected DbSet<T> DbSet;

        public IQueryable<T> AsNoTracking()
        {
            return DbSet.AsNoTracking<T>();
        }

        public virtual T GetById(string id)
        {
            return DbSet.Find(id);
        }

        public virtual IQueryable<T> GetMany(Expression<Func<T, bool>> where)
        {
            return DbSet.Where(where);
        }

        public virtual void Add(T entity)
        {
            entity.IsDeleted = false;

            DbSet.Add(entity);
        }

        public virtual void Update(T entity)
        {
            // Don't need to call this function if AutoDetectChangesEnabled is enabled
            DbSet.Attach(entity);
            DbContext.Entry(entity).State = EntityState.Modified; // be careful with an object has child objects
        }

        public virtual void Delete(T entity)
        {
            entity.IsDeleted = true;

            DbSet.Attach(entity);
            DbContext.Entry(entity).State = EntityState.Modified;
        }
    }
}
